package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证审核表 服务实现类
 * </p>
 *
 * @author jianghaijun
 * @since 2025-10-23
 */
@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {

    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;

    /**
     * 提交服务认证
     * @param agencyCertificationAuditAddReqDTO 认证参数
     */
    @Override
    @Transactional
    public void submit(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        // 保存到认证表
        AgencyCertification agencyCertification = BeanUtils.copyBean(agencyCertificationAuditAddReqDTO, AgencyCertification.class);
        agencyCertification.setId(agencyCertificationAuditAddReqDTO.getServeProviderId());
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setCreateTime(LocalDateTime.now());
        agencyCertification.setUpdateTime(LocalDateTime.now());
        agencyCertificationMapper.insert(agencyCertification);

        // 保存到审核表
        // 拷贝参数
        AgencyCertificationAudit agencyCertificationAudit = BeanUtils.copyBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);
        agencyCertificationAudit.setAuditStatus(AuditStatusEnum.NOT_AUDIT.getStatus()); // 未审核
        agencyCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus()); // 认证中...
        agencyCertificationAudit.setCreateTime(LocalDateTime.now());
        agencyCertificationAudit.setUpdateTime(LocalDateTime.now());
        baseMapper.insert(agencyCertificationAudit);
    }

    /**
     * 查询最新的驳回原因
     * @return 驳回原因
     */
    @Override
    public String rejectReason() {
        // 获取登录Id
        Long id = UserContext.getCurrentUser().getId();
        // 查询条件
        LambdaQueryWrapper<AgencyCertificationAudit> wrapper = Wrappers.lambdaQuery(AgencyCertificationAudit.class)
                .select(AgencyCertificationAudit::getRejectReason)
                .eq(AgencyCertificationAudit::getServeProviderId, id)
                .orderByDesc(AgencyCertificationAudit::getCreateTime)
                .last("LIMIT 1");
        AgencyCertificationAudit audit = baseMapper.selectOne(wrapper);
        return ObjectUtils.isNotEmpty(audit) ? audit.getRejectReason() : "";
    }

    /**
     * 分页查询认证审核
     * @param agencyCertificationAuditPageQueryReqDTO 分页参数
     * @return 分页数据
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> page(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        Page<AgencyCertificationAudit> agencyCertificationAuditPage = baseMapper.selectPage(PageUtils.parsePageQuery(agencyCertificationAuditPageQueryReqDTO, AgencyCertificationAudit.class), Wrappers.lambdaQuery());
        return PageUtils.toPage(agencyCertificationAuditPage, AgencyCertificationAuditResDTO.class);
    }

    /**
     * 审核机构认证信息
     * @param id 认证id
     * @param certificationStatus 认证状态
     * @param rejectReason 驳回原因
     */
    @Override
    @Transactional
    public void audit(Long id, Integer certificationStatus, String rejectReason) {

        // 更新审核表
        AgencyCertificationAudit agencyCertificationAudit = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(agencyCertificationAudit)) {
            throw new BadRequestException("不存在该审核信息！");
        }
        agencyCertificationAudit.setCertificationStatus(certificationStatus); // 根据传入的认证状态设置
        agencyCertificationAudit.setAuditStatus(AuditStatusEnum.AUDITED.getStatus()); // 设置已审核
        // 当驳回时，需要传驳回原因
        if (certificationStatus == CertificationStatusEnum.FAIL.getStatus() && StringUtils.isEmpty(rejectReason)) {
            throw new BadRequestException("请选择/输入驳回原因！");
        }
        agencyCertificationAudit.setRejectReason(rejectReason); // 设置驳回原因
        agencyCertificationAudit.setAuditorId(UserContext.getCurrentUser().getId()); // 设置审核人id
        agencyCertificationAudit.setAuditorName(UserContext.getCurrentUser().getName()); // 设置审核人姓名
        agencyCertificationAudit.setAuditTime(LocalDateTime.now()); // 设置审核时间
        agencyCertificationAudit.setUpdateTime(LocalDateTime.now()); // 设置更新时间

        baseMapper.updateById(agencyCertificationAudit);

        // 更新认证表
        AgencyCertification agencyCertification = agencyCertificationMapper.selectById(agencyCertificationAudit.getServeProviderId());
        if (ObjectUtils.isEmpty(agencyCertification)) {
            throw new BadRequestException("不存在该认证信息！");
        }
        agencyCertification.setCertificationStatus(certificationStatus); // 设置认证状态
        agencyCertification.setCertificationTime(LocalDateTime.now()); // 设置认证时间
        agencyCertification.setUpdateTime(LocalDateTime.now()); // 设置更新时间
        agencyCertificationMapper.updateById(agencyCertification);
    }

}
